package com.greyu.ysj.service.impl;


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.greyu.ysj.entity.CbtNewsExample;
import com.greyu.ysj.config.ResultStatus;
import com.greyu.ysj.entity.CbtNews;
import com.greyu.ysj.mapper.CbtNewsMapper;
import com.greyu.ysj.model.ResultModel;
import com.greyu.ysj.service.CbtNewsService;

@Service
@Transactional
public class CbtNewsServiceImpl implements CbtNewsService {
	@Autowired
	private CbtNewsMapper cbtNewsMapper;

	@Override
	public List<CbtNews> getAllNews(Integer page, Integer rows,int languageFlag) {
		if (null != page && null != rows) {
            PageHelper.startPage(page, rows);
        }
		CbtNewsExample CbtNewsExample = new CbtNewsExample();
		CbtNewsExample.Criteria criteria = CbtNewsExample.createCriteria();
		criteria.andLanguageFlagEqualTo(languageFlag);
		CbtNewsExample.setOrderByClause("`id` DESC");
		List<CbtNews> getAllNews = this.cbtNewsMapper.selectByExample(CbtNewsExample);
        return getAllNews;
	}

	@Override
	public int totalPages(Integer rows) {
		CbtNewsExample CbtNewsExample = new CbtNewsExample();
		long total=this.cbtNewsMapper.countByExample(CbtNewsExample);
//		total/=4;
		int totalPages;
		if(total%rows==0) {
			totalPages=(int) (total/rows);
		}else {
			totalPages=(int) (total/rows)+1;
		}
		return totalPages;
	}
	
	@Override
	public List<CbtNews> getOneNews(Integer page, Integer rows,int languageFlag) {
		
		if (null != page && null != rows) {
            PageHelper.startPage(page, rows);
        }

		CbtNewsExample CbtNewsExample = new CbtNewsExample();
		CbtNewsExample.Criteria criteria = CbtNewsExample.createCriteria();
		criteria.andLanguageFlagEqualTo(languageFlag);
    	/*Date date = new Date();
    	Calendar c = Calendar.getInstance();
        c.setTime(date);  
        c.add(Calendar.DATE, -10); 
    	criteria.andCreateDateBetween(c.getTime(), date);*/
    	CbtNewsExample.setOrderByClause("`id` DESC");
        List<CbtNews> cbtNewsList = this.cbtNewsMapper.selectByExample(CbtNewsExample);
        return cbtNewsList;
	}

	@Override
	public ResultModel save(CbtNews cbtNews) {
		try {
		if(cbtNews.getTitle()==null||cbtNews.getContent()==null
				||cbtNews.getLanguageFlag()==null) {
			 return ResultModel.error(ResultStatus.DATA_NOT_NULL);
		}
			this.cbtNewsMapper.insert(cbtNews);
		} catch (Exception e) {
			return ResultModel.error(ResultStatus.INSERT_ERROR);
		}
	        return ResultModel.ok(cbtNews);
		}


}
